package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.CheckBox;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.SysRole;
import com.cy.pj.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    public SysRoleServiceImpl(SysRoleDao sysRoleDao, SysRoleMenuDao sysRoleMenuDao) {
        this.sysRoleDao = sysRoleDao;
        this.sysRoleMenuDao = sysRoleMenuDao;
    }

    @Override
    public int saveRole(SysRole entity) {
        //1.参数校验(自己校验)
        //2.保存角色自身信息
        int rows = sysRoleDao.insertRole(entity);
        //3.保存角色和菜单关系数据
        sysRoleMenuDao.insertRoleMenus(entity.getId(), entity.getMenuIds());
        return rows;
    }

    @Override
    public int updateRole(SysRole entity) {
        //1.参数校验(自己校验)
        //2.保存角色自身信息
        int rows = sysRoleDao.updateRole(entity);
        if (rows == 0)
            throw new ServiceException("记录可能已经不存在");
        //3.更新角色和菜单关系数据
        sysRoleMenuDao.deleteByRoleId(entity.getId());
        //System.out.println("menuIds="+Arrays.toString(menuIds));
        sysRoleMenuDao.insertRoleMenus(entity.getId(), entity.getMenuIds());
        return rows;
    }

    @Override
    public SysRole findById(Integer roleId) {
        SysRole role = sysRoleDao.selectById(roleId);//id,name,note
        if (role == null)
            throw new ServiceException("记录可能已经不存在");
        final List<Integer> menuIds = sysRoleMenuDao.selectById(roleId);
        role.setMenuIds(menuIds);
        return role;
    }

    @Override
    public List<SysRole> findRoles(SysRole entity) {
        return sysRoleDao.selectRoles(entity);
    }

    @Override
    public List<CheckBox> findCheckRoles() {
        //....
        return sysRoleDao.selectCheckRoles();
    }
}
